package cn.tedu.service;

import cn.tedu.entity.Order;
import cn.tedu.feign.AccountClient;
import cn.tedu.feign.EasyIdClient;
import cn.tedu.feign.StorageClient;
import cn.tedu.mapper.OrderMapper;
import cn.tedu.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author Administrator
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private OrderTccAction orderTccAction;
    @Override
    @GlobalTransactional  //启动全局事务
    public void create(Order order) {
        // 远程调用ID发号器,获取订单ID
        Long id = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(id);
        // 不直接完成业务数据操作而是调用tcc的第一阶段方法
        //orderMapper.create(order);
        /**
         * orderTccAction  实例,是动态代理对象
         * 用AOP添加了切面代码,会创建上下文对象,然后传入原始方法
         */
        orderTccAction.prepare(null, order.getId(), order.getUserId(), order.getProductId(), order.getCount(), order.getMoney());


        //远程调用库存,减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用账户,扣减账户
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
